package com.example.shrio;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.example.publice.error.LoginNullUserException;
import com.example.publice.error.LoginPassWordException;
import com.example.util.APIState;

/**
 * 全局異常處理
 * 
 * @author wangkai
 *
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView();
		FastJsonJsonView view = new FastJsonJsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (ex instanceof UnauthenticatedException) {
			attributes.put("code", APIState.S98.getCode());
			attributes.put("msg", "凭证失效");
		} else if (ex instanceof UnauthorizedException) {
			attributes.put("code", APIState.S99.getCode());
			attributes.put("msg", "用户无权限");
		} else if (ex instanceof LoginNullUserException) {
			attributes.put("code", APIState.S01.getCode());
			attributes.put("msg", ex.getMessage());
		} else if (ex instanceof LoginPassWordException) {
			attributes.put("code", APIState.S01.getCode());
			attributes.put("msg", ex.getMessage());
		} else if (ex instanceof LockedAccountException) {
			attributes.put("code", APIState.S01.getCode());
			attributes.put("msg", ex.getMessage());
		} else {
			attributes.put("code", APIState.S500.getCode());
			attributes.put("msg", ex.getMessage());
		}
		System.err.println(ex);
		view.setAttributesMap(attributes);
		mv.setView(view);
		return mv;
	}

}
